package com.jy.api.controller.member;

import com.jy.api.exception.MyException;
import com.jy.api.service.MemberService;
import com.jy.api.signUpReq.member.MemberSignUpReq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * Created by lihu on 2017/12/1.
 */
@Slf4j
@RestController
@RequestMapping(value = "/v1/member", produces = "application/json;charset=utf-8")
public class MembrDetailsController {


    @Autowired
    MemberService memberService;


    /***
     * 获取会员详情
     * @param openid
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/{openid}")
    public ResponseEntity getMemberInfo(@PathVariable String openid) {
        try {
            return ResponseEntity.ok(memberService.getMemberInfo(openid));
        } catch (Exception ex) {
            log.error("getMemberInfo is error==> openid:{}", openid, ex);
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }



    /***
     * 获取会员详情
     * @param memberId
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/{memberId}/myShelf")
    public ResponseEntity getMemberInfo(@PathVariable String memberId,@RequestParam("storeId")String storeId) {
        try {
            return ResponseEntity.ok(memberService.getMemberInfoByStoreId(memberId,storeId));
        } catch (Exception ex) {
            log.error("getMemberInfo is error==> openid:{}", memberId, ex);
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }


    /**
     * 修改会员信息
     *
     * @param memberSignUpReq
     * @param bindingResult
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/{openid}")
    public ResponseEntity updateMemberInfo(@Valid @RequestBody MemberSignUpReq memberSignUpReq,
                                           BindingResult bindingResult) {
        try {
            if (bindingResult.hasErrors()) {
                log.error("【修改会员】参数不正确, memberSignUpReq={}", memberSignUpReq);
                return new ResponseEntity(bindingResult.getFieldError().getDefaultMessage(), HttpStatus.BAD_REQUEST);
            }
            memberService.updateMember(memberSignUpReq);
            return ResponseEntity.ok("");
        } catch (MyException ex) {
            log.error("updateMemberInfo is error==> memberSignUpReq:{}", memberSignUpReq, ex);
            return new ResponseEntity(ex.getMessage(), HttpStatus.BAD_REQUEST);
        } catch (Exception ex) {
            log.error("updateMemberInfo is error==> memberSignUpReq:{}", memberSignUpReq, ex);
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

}
